package net.adetech.crj.web;


import com.alibaba.fastjson.JSON;
import net.adetech.crj.entity.Hall;
import net.adetech.crj.entity.User;
import net.adetech.crj.utils.ServiceUtil;
import net.adetech.framework.entity.ServiceResponse;
import net.adetech.framework.utils.DistanceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
public class HallMapWebController {

    @Autowired
    ServiceUtil serviceUtil;


    @RequestMapping(value = "/hall/page/map")
    public String hallMap(Model model, HttpSession session,String hallId)
    {

        User user = (User)session.getAttribute("currentUser");






        ServiceResponse response = serviceUtil.callService("hall.getAll");
        List<Hall> hallList = (List<Hall>)response.get("hallList");
        List<Hall> resultList = new LinkedList<Hall>();
        for (Hall hall:hallList) {
            double distance = DistanceUtil.getDistance(user.getLat(),user.getLng(),hall.getLatitude(),hall.getLongitude());
            hall.setDistance(distance);
            if ("1".equals(user.getUserType()))
            {
                resultList.add(hall);
            }
            else {
                if (hall.getServiceFlagB())
                {
                    resultList.add(hall);
                }
            }
        }



        Collections.sort(resultList, new Comparator<Hall>() {
            @Override
            public int compare(Hall h1, Hall h2) {
                if (h1.getDistance()>h2.getDistance())
                {
                    return 1;
                }else {
                    return -1;
                }
            }
        });


        String hallListString = JSON.toJSONString(resultList);






        String params = "var hallList = "+hallListString+";\n";
        params+="var userLat = "+user.getLat()+";\n";
        params+="var userLng = "+user.getLng()+";\n";
        if (hallId!=null)
        {
            params+="var targetId = "+hallId+";\n";

        }

        model.addAttribute("params",params);
        return "hallMap";
    }
}


